<template>
	<view class="order-detail-container">
		<!-- 顶部导航 -->
		<view class="nav-bar">
			<view class="nav-back" @click="goBack">
				<uni-icons type="arrowleft" size="24" color="#fff"></uni-icons>
			</view>
			<text class="nav-title">{{studentName}}的零食订单</text>
			<view class="nav-placeholder"></view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y>
			<!-- 全选操作栏 -->
			<view class="select-all-bar" v-if="hasUnpaidOrders">
				<label class="select-all-checkbox">
					<checkbox-group @change="toggleSelectAll">
						<checkbox :checked="isAllSelected" color="#4a8fe7" />
					</checkbox-group>
					<text class="select-all-text">全选</text>
				</label>
				<text class="select-count">已选{{selectedCount}}件</text>
			</view>

			<!-- 合并后的订单分组 -->
			<view class="order-group" v-for="(group, groupIndex) in mergedOrderGroups" :key="groupIndex">
				<view class="order-card">
					<view class="order-header">
						<view class="order-time">
							<uni-icons type="calendar" size="16" color="#999"></uni-icons>
							<text class="order-date">{{formatDate(group.createTime)}}</text>
						</view>
						<view class="order-status" :class="'status-' + group.paymentStatus">
							{{getStatusText(group.paymentStatus)}}
						</view>
					</view>

					<view class="order-content">
						<view class="product-list">
							<view class="product-card" v-for="(item, i) in group.items" :key="i">
								<view class="product-select" v-if="item.paymentStatus === 0">
									<checkbox-group @change="(e) => toggleSelectItem(item.id, e)">
										<checkbox :checked="selectedOrders.includes(item.id)" color="#4a8fe7" />
									</checkbox-group>
								</view>
								<image class="product-image" :src="getImageUrl(item.snackImage)" mode="aspectFill">
								</image>
								<view class="product-info">
									<text class="product-name">{{item.snackName}}</text>
									<view class="product-meta">
										<text class="product-price">¥{{item.price.toFixed(2)}}</text>
										<text class="product-quantity">×{{item.quantity || 1}}</text>
									</view>
								</view>
								<view class="product-actions" v-if="item.paymentStatus === 0">
									<button class="delete-btn" @click.stop="deleteOneItem(item)">
										<text class="delete-text">删除一个</text>
									</button>
								</view>
							</view>
						</view>

						<view class="order-summary">
							<text class="summary-text">共{{calculateTotalQuantity(group.items)}}件商品</text>
							<text class="summary-amount">合计: ¥{{calculateTotalAmount(group.items)}}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 无订单提示 -->
			<view class="empty-state" v-if="orders.length === 0 && !loading">
				<image class="empty-image" src="/static/empty-order.png" mode="aspectFit"></image>
				<text class="empty-title">暂无订单记录</text>
				<text class="empty-subtitle">该学生还没有零食订单</text>
			</view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="action-bar" v-if="hasUnpaidOrders">
			<view class="total-section">
				<text class="total-label">总计:</text>
				<text class="total-price">¥{{calculateSelectedAmount()}}</text>
			</view>
			<button class="confirm-btn" @click="confirmPayment" :disabled="selectedCount === 0">
				<text>确认支付</text>
				<uni-icons type="arrowright" size="18" color="#fff"></uni-icons>
			</button>
		</view>

		<!-- 加载状态 -->
		<view class="loading-state" v-if="loading">
			<uni-load-more status="loading" iconType="circle" color="#4a8fe7"></uni-load-more>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				studentId: '',
				studentName: '',
				orders: [],
				loading: false,
				selectedOrders: [] // 存储选中的订单ID
			}
		},

		computed: {
			// 合并相同零食并按时间分组
			mergedOrderGroups() {
				// 1. 先按支付状态和时间分组（允许前后2秒误差）
				const timeGroups = {};
				this.orders.forEach(order => {
					const timeKey =
						`${order.paymentStatus}-${Math.floor(new Date(order.createdAt).getTime() / 2000) * 2000}`;
					if (!timeGroups[timeKey]) {
						timeGroups[timeKey] = {
							createTime: order.createdAt,
							paymentStatus: order.paymentStatus,
							items: []
						};
					}
					timeGroups[timeKey].items.push(order);
				});

				// 2. 在每个时间组内合并相同零食
				const mergedGroups = [];
				Object.values(timeGroups).forEach(group => {
					const snackMap = {};
					group.items.forEach(order => {
						if (!snackMap[order.snackId]) {
							snackMap[order.snackId] = {
								...order,
								quantity: 1,
								originalIds: [order.id]
							};
						} else {
							snackMap[order.snackId].quantity += 1;
							snackMap[order.snackId].originalIds.push(order.id);
						}
					});

					// 将合并后的零食添加到结果中
					mergedGroups.push({
						...group,
						items: Object.values(snackMap)
					});
				});

				// 3. 按时间倒序排序
				return mergedGroups.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
			},

			// 检查是否有未支付的订单
			hasUnpaidOrders() {
				return this.orders.some(order => order.paymentStatus === 0);
			},

			// 获取未支付的订单列表
			unpaidOrders() {
				return this.orders.filter(order => order.paymentStatus === 0);
			},

			// 是否全选
			isAllSelected() {
				return this.unpaidOrders.length > 0 &&
					this.unpaidOrders.every(order => this.selectedOrders.includes(order.id));
			},

			// 已选订单数量
			selectedCount() {
				return this.selectedOrders.length;
			}
		},

		onLoad(options) {
			this.studentId = options.studentId || '';
			this.studentName = options.studentName || '';
			this.fetchOrders();
		},

		methods: {
			// 获取订单数据
			async fetchOrders() {
				this.loading = true;
				try {
					const res = await uni.request({
						url: `${globalVariable}/getByStudent`,
						method: 'GET',
						data: {
							studentId: this.studentId
						}
					});

					if (res.data && res.data.status === 1) {
						this.orders = res.data.data || [];
						// 默认选中所有未支付的订单
						this.selectedOrders = this.unpaidOrders.map(order => order.id);
					} else {
						uni.showToast({
							title: res.data.message || '获取订单失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取订单失败:', error);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 获取图片URL
			getImageUrl(url) {
				if (!url) return '/static/aver1.jpg';
				if (url.startsWith('http')) return url;
				return `${globalVariable}/getSnackImage/${url}`;
			},

			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				const now = new Date();
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
				const yesterday = new Date(today);
				yesterday.setDate(yesterday.getDate() - 1);

				if (date >= today) {
					return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
				} else if (date >= yesterday) {
					return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
				} else {
					return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
				}
			},

			// 获取订单状态文本
			getStatusText(status) {
				const statusMap = {
					0: '待支付',
					1: '已完成'
				};
				return statusMap[status] || '未知状态';
			},

			// 计算订单组总金额
			calculateTotalAmount(items) {
				return items.reduce((total, item) => total + (item.price * (item.quantity || 1)), 0).toFixed(2);
			},

			// 计算商品总数量
			calculateTotalQuantity(items) {
				return items.reduce((total, item) => total + (item.quantity || 1), 0);
			},

			// 计算选中订单的总金额
			calculateSelectedAmount() {
				let total = 0;
				this.mergedOrderGroups.forEach(group => {
					group.items.forEach(item => {
						if (this.selectedOrders.includes(item.id)) {
							total += item.price * (item.quantity || 1);
						}
					});
				});
				return total.toFixed(2);
			},

			// 切换全选状态
			toggleSelectAll() {
				if (this.isAllSelected) {
					this.selectedOrders = [];
				} else {
					this.selectedOrders = this.unpaidOrders.map(order => order.id);
				}
			},

			// 切换单个订单的选中状态
			toggleSelectItem(orderId, e) {
				const checked = e.detail.value.length > 0;
				if (checked) {
					if (!this.selectedOrders.includes(orderId)) {
						this.selectedOrders.push(orderId);
					}
				} else {
					this.selectedOrders = this.selectedOrders.filter(id => id !== orderId);
				}
			},

			// 删除一个商品
			async deleteOneItem(item) {
				uni.showModal({
					title: '确认删除',
					content: `确定要删除一个${item.snackName}吗？`,
					confirmColor: '#ff6b6b',
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除中...',
								mask: true
							});
							try {

								// 如果只剩一个，直接删除整个订单
								const res = await uni.request({
									url: `${globalVariable}/deleteSnackOrder?orderId=${item.id}`,
									method: 'DELETE',
								});

								if (res.data && res.data.status === 1) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
									// 刷新订单数据
									this.fetchOrders();
								} else {
									uni.showToast({
										title: res.data.message || '删除失败',
										icon: 'none'
									});
								}

							} catch (error) {
								console.error('删除失败:', error);
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			async confirmPayment() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请选择要支付的订单',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '确认支付',
					content: `确定要为${this.studentName}支付¥${this.calculateSelectedAmount()}吗？`,
					confirmColor: '#4a8fe7',
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '支付中...',
								mask: true
							});

							try {
								// 循环发送每个选中的订单
								for (const group of this.mergedOrderGroups) {
									for (const item of group.items) {
										if (this.selectedOrders.includes(item.id)) {
											// 支付所有原始订单
											for (const orderId of item.originalIds) {
												await this.paySingleOrder(orderId);
											}
										}
									}
								}

								uni.showToast({
									title: '支付成功',
									icon: 'success'
								});
								// 刷新订单数据
								this.fetchOrders();
							} catch (error) {
								console.error('支付失败:', error);
								uni.showToast({
									title: '支付失败，请重试',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 新增单个订单支付方法
			async paySingleOrder(orderId) {
				try {
					const res = await uni.request({
						url: `${globalVariable}/updateSnackOrderById?id=${orderId}`,
						method: 'POST'
					});

					if (!(res.data && res.data.status === 1)) {
						throw new Error(res.data?.message || '支付失败');
					}
				} catch (error) {
					console.error(`订单${orderId}支付失败:`, error);
					throw error;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-detail-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f8f9fa;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 15px 20px;
		background: linear-gradient(135deg, #4a8fe7, #6ba8ff);
		color: white;
		box-shadow: 0 2px 10px rgba(74, 143, 231, 0.2);
		position: relative;
		z-index: 10;

		.nav-back {
			width: 24px;
			height: 24px;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.nav-title {
			font-size: 18px;
			font-weight: 600;
			letter-spacing: 0.5px;
		}

		.nav-placeholder {
			width: 24px;
		}
	}

	.select-all-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 20px;
		background-color: #fff;
		border-radius: 12px;
		margin: 15px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		border: 1px solid #f1f5f9;

		.select-all-checkbox {
			display: flex;
			align-items: center;

			.select-all-text {
				font-size: 15px;
				color: #334155;
				margin-left: 8px;
				font-weight: 500;
			}
		}

		.select-count {
			font-size: 14px;
			color: #64748b;
		}
	}

	.order-list {
		flex: 1;
		padding-bottom: 80px;
	}

	.order-group {
		margin: 15px;
	}

	.order-card {
		background-color: #fff;
		border-radius: 12px;
		overflow: hidden;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		border: 1px solid #f1f5f9;

		&:active {
			transform: scale(0.98);
		}
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 20px;
		background-color: #f8fafc;
		border-bottom: 1px solid #f1f5f9;

		.order-time {
			display: flex;
			align-items: center;

			.order-date {
				font-size: 14px;
				color: #64748b;
				margin-left: 8px;
			}
		}

		.order-status {
			padding: 4px 10px;
			border-radius: 12px;
			font-size: 13px;
			font-weight: 500;

			&.status-0 {
				background-color: #fff0f0;
				color: #ff6b6b;
			}

			&.status-1 {
				background-color: #f0f7ff;
				color: #4a8fe7;
			}
		}
	}

	.order-content {
		padding: 0 15px;
	}

	.product-list {
		padding: 10px 0;
	}

	.product-card {
		display: flex;
		align-items: center;
		padding: 15px 0;
		position: relative;

		&:not(:last-child) {
			border-bottom: 1px dashed #f1f5f9;
		}
	}

	.product-select {
		margin-right: 10px;

		checkbox {
			transform: scale(0.9);
		}
	}

	.product-image {
		width: 60px;
		height: 60px;
		border-radius: 8px;
		object-fit: cover;
		background-color: #f8fafc;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
	}

	.product-info {
		flex: 1;
		margin-left: 15px;
		display: flex;
		flex-direction: column;

		.product-name {
			font-size: 15px;
			font-weight: 600;
			color: #334155;
			margin-bottom: 5px;
			display: -webkit-box;
			-webkit-line-clamp: 1;
			-webkit-box-orient: vertical;
			overflow: hidden;
		}

		.product-meta {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.product-price {
				font-size: 16px;
				font-weight: 700;
				color: #ff6b6b;
			}

			.product-quantity {
				font-size: 14px;
				color: #64748b;
			}
		}
	}

	.product-actions {
		margin-left: 15px;

		.delete-btn {
			padding: 4px 10px;
			background-color: #fff0f0;
			border-radius: 15px;
			border: none;
			display: flex;
			align-items: center;

			.delete-text {
				font-size: 12px;
				color: #ff6b6b;
			}

			&::after {
				border: none;
			}
		}
	}

	.order-summary {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding: 12px 0;
		border-top: 1px solid #f1f5f9;

		.summary-text {
			font-size: 14px;
			color: #64748b;
			margin-right: 12px;
		}

		.summary-amount {
			font-size: 16px;
			font-weight: 700;
			color: #4a8fe7;
		}
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 0;

		.empty-image {
			width: 150px;
			height: 150px;
			opacity: 0.6;
			margin-bottom: 20px;
		}

		.empty-title {
			font-size: 16px;
			font-weight: 600;
			color: #64748b;
			margin-bottom: 8px;
		}

		.empty-subtitle {
			font-size: 14px;
			color: #94a3b8;
		}
	}

	.action-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 20px;
		background-color: #fff;
		border-top: 1px solid #f1f5f9;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		z-index: 10;

		.total-section {
			display: flex;
			align-items: baseline;

			.total-label {
				font-size: 14px;
				color: #64748b;
				margin-right: 8px;
			}

			.total-price {
				font-size: 18px;
				font-weight: 700;
				color: #ff6b6b;
			}
		}

		.confirm-btn {
			background: linear-gradient(135deg, #4a8fe7, #6ba8ff);
			color: white;
			border-radius: 25px;
			padding: 0 20px;
			height: 45px;
			line-height: 45px;
			font-size: 15px;
			font-weight: 600;
			display: flex;
			align-items: center;
			border: none;
			box-shadow: 0 4px 12px rgba(74, 143, 231, 0.3);
			transition: all 0.3s ease;

			&[disabled] {
				background: #cbd5e1;
				box-shadow: none;
				transform: none !important;
			}

			&:active {
				transform: scale(0.95);
			}

			uni-icons {
				margin-left: 5px;
			}

			&::after {
				border: none;
			}
		}
	}

	.loading-state {
		padding: 20px 0;
		display: flex;
		justify-content: center;
	}

	@keyframes pulse {
		0% {
			transform: scale(0.95);
			opacity: 0.7;
		}

		70% {
			transform: scale(1.2);
			opacity: 1;
		}

		100% {
			transform: scale(0.95);
			opacity: 0.7;
		}
	}
</style>